package com.chenjt.three_tools;

import com.google.common.collect.Lists;
import dev.langchain4j.agent.tool.Tool;
import dev.langchain4j.agent.tool.ToolExecutionRequest;
import dev.langchain4j.agent.tool.ToolSpecification;
import dev.langchain4j.agent.tool.ToolSpecifications;
import dev.langchain4j.data.message.AiMessage;
import dev.langchain4j.data.message.ToolExecutionResultMessage;
import dev.langchain4j.data.message.UserMessage;
import dev.langchain4j.model.chat.ChatLanguageModel;
import dev.langchain4j.model.ollama.OllamaChatModel;
import dev.langchain4j.model.openai.OpenAiChatModel;
import dev.langchain4j.model.output.Response;

import java.lang.reflect.Method;
import java.time.LocalDateTime;
import java.util.Collections;

/**
 * 注释：
 *
 * @author chenjt
 * @date 2025/3/7 16:00
 */
public class ToolsDemo1 {



    @Tool("获取当前日期")
    public static String dataUtil(){
        return LocalDateTime.now().toString();
    }

    public static void main(String[] args) throws Exception {

//        OllamaChatModel model = OllamaChatModel.builder()
//                .baseUrl("http://188.88.3.65:11435")
//                .modelName("deepseek-r1:1.5b")
//                .build();

        ChatLanguageModel model = OpenAiChatModel.builder()
                .apiKey("demo")
                .modelName("gpt-4o-mini")
                .build();

        ToolSpecification toolSpecification =
                ToolSpecifications.toolSpecificationFrom(ToolsDemo1.class.getMethod("dataUtil"));

        UserMessage userMessage = UserMessage.from("今天是几月几号");

        Response<AiMessage> aiMessageResponse = model.generate(Collections.singletonList(userMessage), toolSpecification);

        AiMessage aiMessage = aiMessageResponse.content();
        // AiMessage { text = null toolExecutionRequests = [ToolExecutionRequest { id = "call_b7nt8fvQUvTK2RnzQ36ot0KS", name = "dataUtil", arguments = "{}" }] }
        System.out.println(aiMessage);

        if(aiMessage.hasToolExecutionRequests()){
            for(ToolExecutionRequest toolExecutionRequest : aiMessage.toolExecutionRequests()){
                String methodName = toolExecutionRequest.name();
                Method method = ToolsDemo1.class.getMethod(methodName);

                // 执行本地工具方法
                String result = (String)method.invoke(null);
                // 2025-03-07T16:23:34.550401200
                System.out.println(result);

                // 将工具的结果扔给 LLM
                ToolExecutionResultMessage toolExecutionResultMessage = ToolExecutionResultMessage.from(toolExecutionRequest.id(), toolExecutionRequest.name(), result);

                Response<AiMessage> response = model.generate(Lists.newArrayList(userMessage, aiMessage, toolExecutionResultMessage));
                // 今天是2025年3月7日。
                System.out.println(response.content().text());

            }

        }


    }

}
